package com.vincce.sport.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.core.utils.SimpleStorageClient.StorageResult;
import com.vincce.sport.entity.ImgTemp;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.ImgTempMapper;


@Controller
@RequestMapping("/imgTemp")
public class ImgTempController extends BaseController{
	@Resource
	private ImgTempMapper imgTempMapper;

    @RequestMapping("/list")
    public String ImgTempList(Model model, ImgTemp imgTemp, Page<ImgTemp> page) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(imgTemp.getName() != null && !imgTemp.getName().equals("")){
            filter.put("name", imgTemp.getName());
        }
		if(imgTemp.getStatus() != null && !imgTemp.getStatus().equals("")){
			filter.put("status", imgTemp.getStatus());
		}
        page.setFilter(filter);

        page.setResult(replace(imgTempMapper.queryImgTempList(page)));
        page.setTotal(imgTempMapper.queryImgTempCount(page.getFilter()));
        model.addAttribute("page",page);
        
        
//        List<ImgTemp> ImgTempList = imgTempMapper.findAllImgTemp();
//        model.addAttribute("ImgTempList",ImgTempList);
        
        return "backstage/imgTempList";
    }
    
    /**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<ImgTemp> replace(List<ImgTemp> imgTempList){
		if(imgTempList!=null && imgTempList.size()>0){
			for(ImgTemp itl:imgTempList){
				itl.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+itl.getImgPath(), "ori"));
			}
		}
		return imgTempList;
	}
	
	@RequestMapping("/updateStatus")
	@ResponseBody
	public String updateStatus (Model model, ImgTemp imgTemp, HttpServletRequest request) throws IOException{
		Long count = 0l;
		Map<String, Object> result = new HashMap<String, Object>();
		count = imgTempMapper.updateImgTemp(imgTemp);
		result.put("suc", count > 0 ? true : false);
	    return JSON.toJSONString(result);
	}

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateImgTemp(Model model, ImgTemp imgTemp, HttpServletRequest request) throws IOException{
        Long count = 0l;
     // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：     
        MultipartFile file = multipartRequest.getFile("file");
        StorageResult obj = new StorageResult(200, "");
        
        Map<String, Object> result = new HashMap<String, Object>();
        if(CheckUtil.isEmpty(imgTemp.getId())){
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					 obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
					 if (obj.statusCode == 200) {
						    String path= obj.info.replaceAll("\\\\", "/");
						    imgTemp.setImgPath(path);
						    count = imgTempMapper.insertImgTemp(imgTemp);
		              }
				}
            }else{
            	result.put("msg","请选择文件!");
                result.put("suc", false);
            }
        } else{
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
	                if (obj.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	imgTemp.setImgPath(path);
	                	count = imgTempMapper.updateImgTemp(imgTemp);
	                }
				}
            } else {
            	count = imgTempMapper.updateImgTemp(imgTemp);
            }
        }

        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteImgTemp(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;

        imgTempMapper.deleteById(id);

        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    /**
     * 檢查模版名是否已存在
     * @param resourceName
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkImgTempName")
    @ResponseBody
    public String checkImgTempName(String name,Long id) throws Exception{
        ImgTemp imgTemp =new ImgTemp();
        if(name != null && !name.equals("")){
        	imgTemp.setName(name);
        }
        if(id!= null && !id.equals("")){
        	imgTemp.setId(id);
        }
        Integer fg = 0;
        List<ImgTemp> ImgTempList = imgTempMapper.findImgTempByOne(imgTemp);
        if(ImgTempList!=null && ImgTempList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
}
